// pages/coupon/coupon_store.js
var app = getApp();
const DrainageScene = require('../../utils/drainage_scene.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    coupon_list: [],
    page: 1,
    goload: true,
    total_page: 0,
    loading: true,
    allLoaded: false,
    isLoadMore: true,
    types: [],
    typesIndex: 0,
    kFootshow: true,
    coupon_form: '',
    visibleIntegralPopup: false,
    exchangeForm: {},
    integralPluginName: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._initData();
    this._getNetData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },
  //右下角悬浮按钮
  gocouponStore() {
    wx.redirectTo({
      url: '/packageA/member/coupon_v2/coupon_v2',
    });
  },
  tapurl(e) {
    console.log(e.currentTarget.dataset.link);
    let link = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: link,
    });
  },
  setTypesIndex(evt) {
    let index = evt.currentTarget.dataset.index;
    if (index == this.data.typesIndex) return;
    this.setData({
      typesIndex: index
    });
    this._getNetData();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this._initData();
    this._getNetData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData(this.data.page);
    } else {
      console.log('没有更多数据');
      // wx.showToast({
      // 	title: '没有更多数据',
      // 	icon: 'none',
      // 	duration: 1000
      // })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  _initData() {
    this.setData({
      coupon_list: [],
      page: 1,
      goload: true,
      total_page: 0,
      loading: true,
      allLoaded: false,
      isLoadMore: true
    });
  },
  _getNetData() {
    let that = this;
    let urlStr = app.getNetAddresss("coupon.member-coupon.coupons-for-member");

    if (app.globalData.store_alone_temp == 1) {
      // 开启门店独立模块
      urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.coupon.coupons-for-member");
    }

    urlStr += "&page=" + that.data.page;
    urlStr += "&coupon_type=" + that.data.typesIndex;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          var myData = res.data;
          console.log(myData);
          for (let i = 0; i < myData.data.data.length; i++) {
            let couponItem = myData.data.data[i];
            // 是否显示积分兑换
            couponItem.isIntegralExchange = (couponItem.is_integral_exchange_coupon != 0) && (couponItem.exchange_coupon_integral > 0);

            if (couponItem.coupon_type_name == '平台商品') {
              couponItem.type = 1;
            } else if (couponItem.coupon_type_name == '兑换券') {
              couponItem.type = 2;
            } else if (couponItem.coupon_type_name == '分类商品') {
              couponItem.type = 3;
            } else if (couponItem.coupon_type_name == '指定商品') {
              couponItem.type = 4;
            } else if (couponItem.coupon_type_name == '酒店商品') {
              couponItem.type = 5;
            } else if (couponItem.coupon_type_name == '门店商品') {
              couponItem.type = 6;
            } else if (couponItem.coupon_type_name == '商品和门店') {
              couponItem.type = 8;
            }
          }
          that.setData({
            total_page: res.data.data.last_page,
            coupon_list: myData.data.data,
            types: (myData.search_array instanceof Object)?Object.values(myData.search_array):myData.search_array,
            slide_shows: myData.slide_shows,
            integralPluginName: myData.integral_plugin_name ? myData.integral_plugin_name : '消费积分'
          });

          if (that.data.page >= res.data.data.last_page) {
            that.setData({
              isLoadMore: false
            });
          }
          if (res.data.coupon_form) {
            // 插件 领券中心表单
            that.setData({
              coupon_form: res.data.coupon_form
            });
          }
        } else {
          that.setData({
            coupon_list: res.data
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
        wx.stopPullDownRefresh();
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  selectedcoupon(type_in, item, index) {
    let isBindDrainageScene = DrainageScene.bindDrainageScene({
      scene: 3,
      title: '领取优惠券'
    });
    if(!isBindDrainageScene) return;//爆客码绑定场景
    
    // 关闭积分兑换
    if (!item.isIntegralExchange) {
      if (!app._isTextEmpty(this.data.coupon_form)) {
        wx.navigateTo({
          url: '/packageC/diyform/diyform?scene=' + this.data.coupon_form + '&tag=coupon',
        });
        return;
      }
      if (type_in == 2) {
        wx.navigateTo({
          url: '/packageE/team_sell/getCouponShare/getCouponShare?id=' + item.id,
        });
        return;
      }
    }
    //领取
    let that = this;
    let urlStr = app.getNetAddresss("coupon.member-coupon.get-coupon");
    urlStr += "&coupon_id=" + item.id;

    if (item.isIntegralExchange && this.data.exchangeForm.couponTotal > 0) {
      urlStr += "&exchange_total=" + this.data.exchangeForm.couponTotal;
    }
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          var temp = res.data;
          let list = that.data.coupon_list;
          temp.isIntegralExchange = (temp.is_integral_exchange_coupon != 0) && (temp.exchange_coupon_integral > 0);
          list[index] = temp;
          for (let i = 0; i < list.length; i++) {
            if (list[i].coupon_type_name == '平台商品') {
              list[i].type = 1;
            } else if (list[i].coupon_type_name == '兑换券') {
              list[i].type = 2;
            } else if (list[i].coupon_type_name == '分类商品') {
              list[i].type = 3;
            } else if (list[i].coupon_type_name == '指定商品') {
              list[i].type = 4;
            } else if (list[i].coupon_type_name == '酒店商品') {
              list[i].type = 5;
            } else if (list[i].coupon_type_name == '门店商品') {
              list[i].type = 6;
            } else if (list[i].coupon_type_name == '商品和门店') {
              list[i].type = 8;
            }
          }
          wx.showToast({
            title: item.isIntegralExchange?'兑换成功':'领取成功',
            icon: 'none',
            duration: 1000
          });
          that.setData({
            coupon_list: list
          });
          // that._getNetData();
        } else {
          wx.showModal({
            title: res.data.reason?res.msg:'',
            content: res.data.reason?res.data.reason:res.msg,
            showCancel: false
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  selectedcouponBtn(e) {
    // let type_in = e.currentTarget.dataset.item.use_type;
    wx.navigateTo({
      url: '/packageE/team_sell/getCouponShare/getCouponShare?id=' + item.id,
    });
  },
  _getMoreData(page) {
    if (this.data.page == this.data.total_page) {
      this.setData({
        loading: true,
        allLoaded: true,
        isLoadMore: false
      });
      return;
    }
    var that = this;
    let urlStr = app.getNetAddresss("coupon.member-coupon.coupons-for-member");

    if (app.globalData.store_alone_temp == 1) {
      // 开启门店独立模块
      urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.coupon.coupons-for-member");
    }

    if (this.data.page >= this.data.total_page) {
      that.setData({
        loading: true,
        allLoaded: true
      });
      return;
    } else {
      that.setData({
        page: this.data.page + 1
      });
      urlStr += "&page=" + that.data.page;
      urlStr += "&coupon_type=" + that.data.typesIndex;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let myData = res.data;
            for (let i = 0; i < myData.data.data.length; i++) {
              let couponItem = myData.data.data[i];
              couponItem.isIntegralExchange = (couponItem.is_integral_exchange_coupon != 0) && (couponItem.exchange_coupon_integral > 0);
              if (couponItem.coupon_type_name == '平台商品') {
                couponItem.type = 1;
              } else if (couponItem.coupon_type_name == '兑换券') {
                couponItem.type = 2;
              } else if (couponItem.coupon_type_name == '分类商品') {
                couponItem.type = 3;
              } else if (couponItem.coupon_type_name == '指定商品') {
                couponItem.type = 4;
              } else if (couponItem.coupon_type_name == '酒店商品') {
                couponItem.type = 5;
              } else if (couponItem.coupon_type_name == '门店商品') {
                couponItem.type = 6;
              } else if (couponItem.coupon_type_name == '商品和门店') {
                couponItem.type = 8;
              }
            }
            if (res.data.coupon_form) {
              // 插件 领券中心表单
              that.setData({
                coupon_form: res.data.coupon_form
              });
            } else {
              that.setData({
                coupon_form: ''
              });
            }
            that.setData({
              loading: false,
              allLoaded: false,
              coupon_list: that.data.coupon_list.concat(myData.data.data),
            });
          } else {
            that.setData({
              page: that.page - 1,
              loading: true,
              allLoaded: true,
              isLoadMore: false
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  claim(evt) {
    console.log(evt);
    let index = evt.detail.index;
    let item = evt.detail.item;
    let type_in = evt.detail.item.use_type;
    this.selectedcoupon(type_in, item, index);
  },
  tabrshowbtn(e) {
    let bol = e.detail;
    if (bol) {
      this.setData({
        kFootshow: false
      });
    }
  },

  showIntegralPopup (evt) {
    let index = evt.detail.index;
    let item = evt.detail.item;
    let type_in = evt.detail.item.use_type;
    let form = {
      couponTotal: 1,
      exIntegral: item.exchange_coupon_integral
    };
    this.setData({
      exchangeForm: form,
      visibleIntegralPopup: true,
      callbackFn: this.selectedcoupon.bind(this, type_in, item, index)
    });
  },
  // 步进器
  changeTotal (e) {
    this.setData({
      'exchangeForm.couponTotal': e.detail
    });
  },

  cancelExchange () {
    this.setData({visibleIntegralPopup: false});
  },

  exchangeCoupon () {
    if (this.data.exchangeForm.couponTotal <= 0) {
      return wx.showToast({
        title: '请输入兑换优惠券的数量！',
      });
    }
    this.data.callbackFn();
    this.setData({visibleIntegralPopup: false});
  },
});